package com.trw.trp.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.trw.trp.bean.WorkflowBean;
import com.utuan.log.Log;
import com.utuan.log.LogFactory;

public class WorkflowDao extends AbstractDao {

	private static Log log = LogFactory.getLog(WorkflowDao.class);

	private static final String SQL_GET_WF = "SELECT w.workflow_name,ws.status_id,ws.status_name,ws.next_status FROM trp.workflows w, trp.wf_status ws where w.workflow_id=? and w.workflow_id=ws.workflow_id order by ws.status_order";

	WorkflowDao() {
	}

	public WorkflowBean getWorkflow(long workflowId) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		WorkflowBean ret = null;
		try {
			conn = getConnection();
			ps = conn.prepareStatement(SQL_GET_WF);
			ps.setLong(1, workflowId);
			rs = ps.executeQuery();
			String wfName;
			int wfStatusId;
			String wfStatusName;
			int wfNextStatus;
			List<WorkflowBean.Status> statusList = null;
			;
			while (rs.next()) {
				int i = 1;
				wfName = rs.getString(i++);
				wfStatusId = rs.getInt(i++);
				wfStatusName = rs.getString(i++);
				wfNextStatus = rs.getInt(i++);
				if (ret == null) {
					ret = new WorkflowBean();
					ret.setWorkflowId(workflowId);
					ret.setWorkflowName(wfName);
					statusList = new ArrayList<WorkflowBean.Status>();
					ret.setStatusList(statusList);
				}
				WorkflowBean.Status status = new WorkflowBean.Status();
				status.setStatusId(wfStatusId);
				status.setStatusName(wfStatusName);
				status.setNextStatus(wfNextStatus);
				statusList.add(status);
			}
		} catch (SQLException e) {
			log.warn(e);
			try {
				conn.rollback();
			} catch (SQLException e1) {
				log.warn(e1);
			}
		} finally {
			close(conn, rs, ps);
		}
		return ret;
	}
}
